package cn.wit.luohui.day09;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import org.junit.Test;

//ckecked exception:受检异常。编译的时候会强制你处理
//1.要么在当前的方法里面try catch
//2.要么你往上抛，让调用的人去处理

//RuntimeException:运行的时候才出现
public class DemoCheckedException {
	public static void main(String[] args) {
	File file=new File("d:\\test.java");
	
	 
		try {
			file.createNewFile();//先创建新文件，后自动生成try
			
		} catch (IOException e) {
			System.out.println("创建文件失败！");
			e.printStackTrace();
		}
		System.out.println("异常处理完毕");
	
	}
	/**
	 * 文件读取，演示受检异常的处理流程
	 * @throws IOException
	 */
@Test
public void testFileRead() {
	FileReader reader=null;//安全
	
	try {
		reader=new FileReader("E:\\camocode\\campa\\code\\src\\cn\\wit\\luohui\\day08\\WordCount.java");
	
		char[] chars=new char[100];//防止溢出
		int count=reader.read(chars);
		
		System.out.println(new String(chars));//创建了String放chars,即将chars转为String类型
	} catch (FileNotFoundException e) {
		
		e.printStackTrace();
		
	} catch (IOException e) {
		
		e.printStackTrace();
	}finally {
		//清理资源
		try {
			if(reader!=null) {
			reader.close();
			}
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		System.out.println("finally...");
	}
}
	@Test
	public void testFileRead2() {
		String file="E:\\camocode\\campa\\code\\src\\cn\\wit\\luohui\\day08\\WordCount.java";
	try(FileReader reader=new FileReader(file)) {
		
	} catch (FileNotFoundException e) {
		
		e.printStackTrace();
	} catch (IOException e1) {
		
		e1.printStackTrace();
	}
	//不需要在finally里面清理资源， java7 
	}
	@Test
	public void testFileRead3() throws IOException {//throws放在方法声明
		String file ="E:\\camocode\\campa\\code\\src\\cn\\wit\\luohui\\day08\\WordCount.java";
		FileReader reader = new FileReader(file);
		
		char[] chars = new char[10];
		int count = reader.read(chars);
		
		System.out.println(new String(chars));
	}
	@Test
	public void test() throws IOException {
		testFileRead3();
	}
	//文件读取
	@Test
	public void test2() {
		String file ="E:\\camocode\\campa\\code\\src\\cn\\wit\\luohui\\day08\\WordCount.java";
	
		List<String>lines=null;
		try {
			lines=Files.readAllLines(Paths.get(file));
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		if (lines == null) return;
		for (String line : lines) {
			System.out.println(line);
		}
	}
	
}

